<template>
  <div class="dashboard-editor-container">

    <div id="divPlugin1" class="plugin" ></div>

    <el-row hidden>
      <el-form :inline="true" :model="hkvInfo" class="demo-form-inline">
        <el-row style="margin-top: 10px;">
          <el-form-item label="ip地址">
            <el-input v-model="hkvInfo.ip" placeholder="ip" style="width: 150px;" readonly></el-input>
          </el-form-item>
          <el-form-item label="端口">
            <el-input v-model="hkvInfo.port" placeholder="port" style="width: 150px;" readonly></el-input>
          </el-form-item>
          <el-form-item label="用户名">
            <el-input v-model="hkvInfo.username" placeholder="username" style="width: 150px;" readonly></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="hkvInfo.password" placeholder="password" style="width: 150px;" readonly></el-input>
          </el-form-item>
        </el-row>
        <el-row style="margin-top: 10px;">
          <el-col>
            <el-form-item>
              <el-button type="primary" :loading="loginLoading" @click="onLogin">登录</el-button>
              <el-button type="primary" :loading="startPlayLoading" @click="clickStartRealPlay">开始预览</el-button>
              <el-button type="primary" @click="clickStopRealPlay">停止预览</el-button>
              <el-button type="primary" @click="onLogout">退出</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-row>
    <el-row hidden>
      <div>
        <label>数字通道列表: </label>
        <el-tag type="success" class="my-tag" v-for="(item,index) in hkvInfo.channels" :key="index">{{item}}</el-tag>
      </div>
    </el-row>

  </div>
</template>

<script>
  import { getVideoInfo } from "@/api/basic/videoInfo";
  const defaultSettings = require('@/settings.js');
  import {WebVideoCtrl} from '@/assets/js/webVideoCtrl.js'

export default {
  name: "VideoShow",
  components: {
  },
  data() {
    return {
      netWork:true,
      // <!-- 视频监控
      hkvInfo: {
        ip: '',//海康威视摄像头/硬盘录像机的ip地址
        port: '',//海康威视摄像头/硬盘录像机的端口
        username: '',//海康威视摄像头/硬盘录像机的用户名
        password: '',//海康威视摄像头/硬盘录像机的密码
        channels: [],//海康威视摄像头/硬盘录像机的通道
      },
      hkvInfoOld: {//退出登入参数
        ip: '',//海康威视摄像头/硬盘录像机的ip地址
        port: '',//海康威视摄像头/硬盘录像机的端口
      },
      mySelectWnd: 0,//当前选中的窗口
      g_bPTZAuto: false,
      iProtocol: 1,
      loginLoading: false,
      startPlayLoading: false,
      iStreamType: 1,
      bZeroChannel: false,
      iRtspPort: 0,
      flag:true,
      isYtFlag:false
      // 视频监控 -->
    };
  },
  created() {
    this.getList();
  },
  mounted: function () {
    this.videoInitPlugin(); // 初始化video界面
  },
  destroyed: function () {
    this.clickStopRealPlay();
    this.onLogout();
  },
  computed: {

  },
  methods: {
    /** 查询视频配置列表 */
    getList() {
      getVideoInfo(7).then(response => {//606水下摄像机
        this.$nextTick(()=>{
          this.clkVideoInfo(response.data)
        })
      });
    },
    clkVideoInfo(videoInfo){
      // console.log('切换登录------------')
      if(videoInfo.isYt == 'Y'){
        this.isYtFlag = true;
      }else{
        this.isYtFlag = false;
      }
      if(this.netWork){
        this.hkvInfo.ip = videoInfo.ipCode;
        this.hkvInfo.port = videoInfo.portCode;
      }else{
        this.hkvInfo.ip = videoInfo.insideIp;
        this.hkvInfo.port = videoInfo.insidePort;
      }
      this.hkvInfo.username = videoInfo.account;
      this.hkvInfo.password = videoInfo.password;
      this.hkvInfo.channels = [];
      this.onLogin();
    },
    // <!-- 视频监控
    onLogin() {
      try {
        let that = this;
        that.loginLoading = true;
        // console.log('开始登录设备')
        // 登录设备
        WebVideoCtrl.I_Login(that.hkvInfo.ip, that.iProtocol, that.hkvInfo.port, that.hkvInfo.username, that.hkvInfo.password, {
          async: true,
          success: function (xmlDoc) {
            // console.log('xmlDoc2', xmlDoc);//不能删除
            //TODO 获取通道信息
            setTimeout(function () {
              that.getChannelInfo();
              that.getDevicePort(that.hkvInfo.ip + "_" + that.hkvInfo.port);
            }, 10);
            setTimeout(function() {
              that.hkvInfoOld.ip = that.hkvInfo.ip;
              that.hkvInfoOld.port = that.hkvInfo.port;
              that.clickStartRealPlay();
            }, 500)
            that.loginLoading = false;
            that.flag = false;
            // that.$message({
            //   showClose: true,
            //   message: '登录成功',
            //   type: 'success'
            // });
          },
          error: function () {
            that.loginLoading = false;
            // console.log('登录失败')
          }
        });
      }catch(err){
        // console.log(err)
      }
    },
    onLogout() {
      if(this.hkvInfoOld.ip != '' && this.hkvInfoOld.port!=''){
        this.hkvInfo.channels = [];
        let szDeviceIdentify = this.hkvInfoOld.ip + "_" + this.hkvInfoOld.port;
        let iRet = WebVideoCtrl.I_Logout(szDeviceIdentify);
        if (0 == iRet) {
          // this.$message({
          //   showClose: true,
          //   message: '退出成功',
          //   type: 'success'
          // });
          this.hkvInfoOld.ip = '';
          this.hkvInfoOld.port = '';
          return true;
        } else {
          // this.$message({
          //   showClose: true,
          //   message: '退出失败',
          //   type: 'error'
          // });
          return false;
        }
      }
    },
    clickStartRealPlay() {
      this.clickStopRealPlay();
      // 开始预览
      let that = this;
      that.startPlayLoading = true;
      let szDeviceIdentify = that.hkvInfo.ip + "_" + that.hkvInfo.port;

      let j = that.hkvInfo.channels.length > 4 ? 4 : that.hkvInfo.channels.length;
      for (let i = 0; i < j; i++) {
        setTimeout(that.startRealPlay(szDeviceIdentify, i, that.hkvInfo.channels[i]), 500);
      }
      that.startPlayLoading = false;
    },
    videoInitPlugin: function () {
      let iRet = WebVideoCtrl.I_CheckPluginInstall();
      if (iRet === -1) {
        alert('您还未安装过插件，双击开发包目录里的WebComponentsKit.exe安装');
        return;
      }
      this.initPlugin()
    },
    initPlugin: function () {
      let that = this;

      WebVideoCtrl.I_InitPlugin(714, 496, {
        bWndFull: true,//是否支持单窗口双击全屏，默I_CheckPluginInstall
        iWndowType: 2,
        myCbSelWnd: function (xmlStr) { //自己新增的方法
          let jsonObj = that.$x2js.xml2js(xmlStr);
          that.mySelectWnd = jsonObj.RealPlayInfo.SelectWnd;
          let szInfo = "当前选择的窗口编号：" + that.mySelectWnd;
          // console.log(szInfo);
        },
        cbInitPluginComplete: function () {
          WebVideoCtrl.I_InsertOBJECTPlugin("divPlugin1");
          //设置窗口1X1
          WebVideoCtrl.I_ChangeWndNum(1);
          // 检查插件是否最新
          if (WebVideoCtrl.I_CheckPluginVersion() === -1) {
            alert("检测到新的插件版本，双击开发包目录里的WebComponentsKit.exe升级！");
            return;
          }
        }
      });
    },
    getDevicePort: function (szDeviceIdentify) {
      let oPort = WebVideoCtrl.I_GetDevicePort(szDeviceIdentify);
      this.iRtspPort = oPort.iRtspPort;
    },
    startRealPlay: function (szDeviceIdentify, iWndIndex, iChannelID) {
      let that = this;
      WebVideoCtrl.I_StartRealPlay(szDeviceIdentify, {
        iRtspPort: that.iRtspPort,
        iWndIndex: iWndIndex,
        iStreamType: 1,
        iChannelID: iChannelID,
        bZeroChannel: that.bZeroChannel,
        success: function () {
          // that.$notify({
          //   title: '成功',
          //   message: '开始预览通道' + iChannelID + '成功',
          //   type: 'success'
          // });
        },
        error: function (status, xmlDoc2) {
          // console.log(xmlDoc2)//不能删除
          // that.$notify({
          //   title: '失败',
          //   message: '开始预览通道' + iChannelID + '失败',
          //   type: 'error'
          // });
          if (status === 403) {
            // console.log("szInfo 设备不支持Websocket取流！");
          } else {
            // console.log("开始预览失败 ", status, xmlDoc2);
          }
        }
      });
    },
    clickStopRealPlay: function () {
      let j = this.hkvInfo.channels.length > 4 ? 4 : this.hkvInfo.channels.length;
      for (let i = 0; i < j; i++) {
        setTimeout(this.stopRealPlay(i), 1000);
      }
    },
    stopRealPlay: function (iWndIndex) {
      let that = this;
      WebVideoCtrl.I_Stop({
        iWndIndex: iWndIndex,
        success: function () {
          // that.$notify({
          //   title: '成功',
          //   message: '停止预览窗口' + iWndIndex + '成功',
          //   type: 'success'
          // });
        },
        error: function () {
          // that.$notify({
          //   title: '失败',
          //   message: '停止预览窗口' + iWndIndex + '失败',
          //   type: 'error'
          // });
        }
      });
    },
    // 获取通道，实际上可以根据自己的项目，获取数字通道，模拟通道，零通道中的一个或多个，不用全部获取（提高效率）
    getChannelInfo: function () {
      let that = this;
      let szDeviceIdentify = this.hkvInfo.ip + "_" + this.hkvInfo.port;
      // debugger
      // 数字通道
      that.hkvInfo.channels = [];
      WebVideoCtrl.I_GetDigitalChannelInfo(szDeviceIdentify, {
          async: false,
          mysuccess: function (xmlStr) {
            // console.log('mysuccess I_GetDigitalChannelInfo: ', xmlStr)
            let jsonObj = that.$x2js.xml2js(xmlStr)
            let list = jsonObj.InputProxyChannelStatusList.InputProxyChannelStatus;
            for (let x = 0; x < list.length; x++) {
              that.hkvInfo.channels.push(list[x].id);
            }
          },
          success: function (xmlDoc) {
          },
          error: function (status, xmlDoc) {
            // console.log("获取数字通道失败");
          }
        }
      );
      // TODO 模拟通道
      // 模拟通道
      WebVideoCtrl.I_GetAnalogChannelInfo(szDeviceIdentify, {
        async: false,
        mysuccess: function (xmlStr) {
          let jsonObj = that.$x2js.xml2js(xmlStr);
          // console.log("模拟通道mysuccess",xmlStr);
          // let list = jsonObj.VideoInputChannelList;
          // for (let x = 0; x < list.length; x++) {
          //   that.hkvInfo.channels.push(list[x].VideoInputChannel.id);
          // }
          var id = jsonObj.VideoInputChannelList.VideoInputChannel.id;
          that.hkvInfo.channels.push(id);
        },
        success: function (xmlStr) {
          // console.log("模拟通道success",xmlStr);
        },
        error: function (status, xmlDoc) {
          // console.log("模拟通道error",xmlDoc);
        }
      });
      // TODO 零通道
    },
    mouseDownPTZControl: function (iPTZIndex) {
      let oWndInfo = WebVideoCtrl.I_GetWindowStatus(this.mySelectWnd);
      if (oWndInfo !== null) {
        if (iPTZIndex === 9 && this.g_bPTZAuto) {
          // iPTZSpeed = 0;
        } else {
          this.g_bPTZAuto = false;
        }

        WebVideoCtrl.I_PTZControl(iPTZIndex, false, {
          iPTZSpeed: 4,
          mysuccess: function (xmlStr) {
            // console.log("I_PTZControl", xmlStr);
            if (iPTZIndex === 9 && this.g_bPTZAuto) {
              // console.log(oWndInfo.szDeviceIdentify + " 停止云台成功！mouseDown");
            } else {
              // console.log(oWndInfo.szDeviceIdentify + " 开启云台成功！mouseDown");
            }
            if (iPTZIndex === 9) {
              this.g_bPTZAuto = !this.g_bPTZAuto;
            }
          },
          error: function (status, xmlDoc) {
            // console.log(oWndInfo.szDeviceIdentify + " 开启云台失败！mouseDown", status, xmlDoc);
          }
        });
      }
    },
    mouseUpPTZControl: function () {
      let oWndInfo = WebVideoCtrl.I_GetWindowStatus(this.mySelectWnd);
      if (oWndInfo !== null) {
        WebVideoCtrl.I_PTZControl(1, true, {
          mysuccess: function (xmlStr) {
            // console.log(oWndInfo.szDeviceIdentify + " 停止云台成功！mouseUp", xmlStr)
          },
          error: function (status, xmlDoc) {
            // console.log(oWndInfo.szDeviceIdentify + " 停止云台失败！mouseUp", status, xmlDoc);
          }
        });
      }
    },
    // 视频监控 -->

  }

}
</script>
<style rel="stylesheet/scss" lang="scss">
  .active{
    color: red;
  }
  .el-dialog:not(.is-fullscreen) {
    margin-top:0vh !important;
  }
</style>
<style scoped>
  .plugin {
    width: 714px;
    height: 496px;
  }

  .my-tag {
    margin-left: 3px;
  }

  .my-group-btn {
    margin-top: 5px;
  }

</style>
<style scoped lang="scss">
  ::v-deep{
    .el-scrollbar__wrap {
      overflow-x: hidden;
    }
  }
</style>
